/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package openyugioh.utils;

import javax.faces.context.FacesContext;
import openyugioh.session.SessionBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 *
 * @author Yeni
 */
public class FacesUtil {
    
    private static ApplicationContext ctx;
    private static final String springXmls = "WEB-INF/applicationContext.xml";
    private static final String LANG = "lang";
    
    private static ApplicationContext getSpringContext() { 
        if (ctx == null) 
            ctx = new ClassPathXmlApplicationContext("file:///" + FacesContext.getCurrentInstance().getExternalContext().getRealPath(springXmls)); 
        return ctx; 
    }
    
    public static Object getSpringBean(String name) {
        return getSpringContext().getBean(name);
    }
    
    public static Object getELValue(String bean, String property) {
        FacesContext context = FacesContext.getCurrentInstance();
        return context.getApplication().evaluateExpressionGet(context, String.format("#{%s.%s}", bean, property), Object.class);
    }

    public static String getLang(String property) {
        return (String)getELValue(LANG, property);
    }
    
    public static SessionBean getSession() {
        FacesContext context = FacesContext.getCurrentInstance();
        if(context != null && context.getExternalContext().getSessionMap() != null) {
            return (SessionBean)context.getExternalContext().getSessionMap().get("sessionBean");
        }
        return null;
    }
    
    public static void redirect(String relativePath) {
        FacesContext context = FacesContext.getCurrentInstance();
//        try {
//            context.getExternalContext().redirect(context.getExternalContext() "" + relativePath);
//        } catch (IOException ex) {
//            Logger.getLogger(FacesUtil.class.getName()).log(Level.SEVERE, null, ex);
//        }
    }
}